package com.wenyu.wenyuyuedu.fragment.circlefragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableListView;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.SearchActivity;
import com.wenyu.wenyuyuedu.activity.personage.Help_FeedBack_Activity;
import com.wenyu.wenyuyuedu.adapter.MyCircleAdapter;
import com.wenyu.wenyuyuedu.bean.circle.MyCircleBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.MyCircleServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 圈子中我的圈子的fragment
 */
public class Personage_Circle_Fragment extends Fragment implements View.OnClickListener {


    @InjectView(R.id.my_content_view)
    PullableListView myContentView;
    @InjectView(R.id.my_refresh_view)
    PullToRefreshLayout myRefreshView;
    @InjectView(R.id.rl_personage_search)
    RelativeLayout rlPersonageSearch;
    @InjectView(R.id.iv_defult)
    ImageView ivDefult;
    @InjectView(R.id.rl_default)
    RelativeLayout rlDefault;
    @InjectView(R.id.tv_error)
    TextView tvError;
    private ListView myListView;
    private Intent intent;
    /*用来区分下拉刷新还是加载更多*/
    private boolean isLoading = false;
    private int page = 1;
    private List<MyCircleBean.InfoBean> info;
    private List<MyCircleBean.InfoBean> infoAll = new ArrayList<>();
    private MyCircleBean bodyPersonage;
    private MyCircleAdapter myCircleAdapter;

    public Personage_Circle_Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_personage__circle_, container, false);
        ButterKnife.inject(this, inflate);
        initClick();
        // requesData();
        return inflate;
    }

    /*初始化根布局的点击事件*/
    private void initClick() {
        intent = new Intent();
        rlPersonageSearch.setOnClickListener(this);
        RefreshAndLoadMore();
    }

    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;


    /*网络请求数据*/
    private void requesData() {
        String token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        if (token != null) {
            MyCircleServer myCircleServer = ApiWrapper.getInstance().create(MyCircleServer.class);
            Call<MyCircleBean> myCircle = myCircleServer.getMyCircle(token, page);
            myCircle.enqueue(new Callback<MyCircleBean>() {
                @Override
                public void onResponse(Call<MyCircleBean> call, Response<MyCircleBean> response) {
                    bodyPersonage = response.body();
                    if (bodyPersonage != null) {
                        int code = bodyPersonage.getCode();
                        if (code == 1) {
                            /*请求成功 */
                            info = bodyPersonage.getInfo();
                            if (info != null) {
                                if (!isLoading) {
                                    infoAll.clear();
                                }
                                infoAll.addAll(info);
                                myCircleAdapter = new MyCircleAdapter(getActivity(), infoAll);
                                myListView.setAdapter(myCircleAdapter);
                                ivDefult.setVisibility(View.GONE);
                                rlDefault.setVisibility(View.GONE);
                            } else {
                                ivDefult.setVisibility(View.VISIBLE);
                            }

                        } else if (code == 0) {
                           /*token错误或者已失效*/
                            //showLoginDialog();
                            rlDefault.setVisibility(View.VISIBLE);
                        } else if (code == 3301) {
                            /*该用户没有添加任何圈子*/
                            //  MyToast.showToast(getActivity(), "暂未关注任何圈子", Toast.LENGTH_SHORT);
                            rlDefault.setVisibility(View.VISIBLE);
                            tvError.setText("暂未关注任何圈子");
                            if (infoAll != null && myCircleAdapter != null) {
                                infoAll.clear();
                                myCircleAdapter.notifyDataSetChanged();
                            }
                        } else if (code == 3400) {
                            /*所有的评论已经全部加载完毕*/
                            MyToast.showToast(getActivity(), "关注的圈子全部展示完毕", Toast.LENGTH_SHORT);
                        }
                    } else {
                        ivDefult.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onFailure(Call<MyCircleBean> call, Throwable t) {
                    MyToast.showToast(getActivity(), "网络异常，请稍后重试", Toast.LENGTH_SHORT);
                    ivDefult.setVisibility(View.VISIBLE);
                }
            });
        }


    }

    /*token错误或者已失效*/
    private void showLoginDialog() {
        ad = new AlertDialog.Builder(getContext()).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                ad.dismiss();
                getActivity().finish();
            }
        });
    }

    /*下拉刷新和加载更多*/
    private void RefreshAndLoadMore() {
        myListView = (ListView) myRefreshView.getPullableView();
        myRefreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page = 1;
                        isLoading = false;
                        requesData();
                        //千万别忘了告诉控件刷新完毕了
                        myRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page++;
                        isLoading = true;
                        requesData();
                        //千万别忘了告诉控件刷新完毕了
                        myRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 100);
            }
        });
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String id = infoAll.get(i).getId();
                String creatorName = infoAll.get(i).getCreatorName();
                String circleName = infoAll.get(i).getTitle();
                String cover = infoAll.get(i).getCover();
                intent.setClass(getActivity(), Help_FeedBack_Activity.class);
                intent.putExtra("creatorName", creatorName);
                intent.putExtra("circleId", id);
                intent.putExtra("circleName", circleName);
                intent.putExtra("circlecover", cover);
                /*创建圈子人的uid*/
                intent.putExtra("myattention", infoAll.get(i).getUid());
                /*当前登录的uid*/
                intent.putExtra("login_find_uid", bodyPersonage.getUser_id());
                startActivity(intent);

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*跳转到搜索界面*/
            case R.id.rl_personage_search:
                intent.setClass(getActivity(), SearchActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        requesData();
    }
}
